<template>
  <div class="chart-container">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <div class="loading-text">数据加载中...</div>
    </div>
    <div ref="chart" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchData } from '../Api/api.js';

export default {
  name: 'NameStatisticsChart',
  data() {
    return {
      nameData: [],     // 存储同名统计数据
      loading: true,    // 加载状态
      chart: null       // ECharts 实例引用
    };
  },
  async mounted() {
    await this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    async fetchData() {
      try {
        this.loading = true;
        const data = await fetchData('getnine');
        this.nameData = data || [];
      } catch (error) {
        console.error('数据加载失败:', error);
        this.nameData = [];
      } finally {
        this.loading = false;
        this.initChart();
      }
    },
    initChart() {
      if (!this.nameData || this.nameData.length === 0) {
        this.showNoData();
        return;
      }

      this.chart = echarts.init(this.$refs.chart);

      // 颜色方案
      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666',
        '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
        '#ea7ccc', '#17b3a3', '#b6a2de', '#5ab1ef'
      ];

      const option = {
        title: {
          text: '同名发送人统计分布',
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold'
          },
          subtext: `共统计 ${this.nameData.length} 个不同姓名`,
          subtextStyle: {
            color: '#666',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>同名人数: {c}',
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderColor: '#333',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 'middle',
          textStyle: {
            color: 'black'
          }
        },
        series: [{
          name: '同名统计',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b|{b}}\n{c|{c}人}',
            rich: {
              b: {
                fontSize: 12,
                lineHeight: 20,
                color: 'black'
              },
              c: {
                fontSize: 11,
                color: '#2b2929'
              }
            }
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 15
          },
          data: this.nameData.map((item, index) => ({
            value: item.cnt,
            name: item.sendername,
            itemStyle: {
              color: colors[index % colors.length]
            }
          }))
        }],
        graphic: this.nameData.length === 0 ? [{
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: '暂无数据',
            fill: 'black',
            fontSize: 16
          }
        }] : undefined
      };

      this.chart.setOption(option);
    },
    showNoData() {
      if (!this.$refs.chart) return;

      this.chart = echarts.init(this.$refs.chart);
      this.chart.setOption({
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: '暂无数据',
            fill: 'black',
            fontSize: 16
          }
        }
      });
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;

  width: 1075px;
  height: 690px;
  min-height: 400px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  box-sizing: border-box;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 350px;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #5470c6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
  color: black;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>